const iconv = require('iconv-lite'); // 导入iconv模块
const crypto = require('crypto');

function checkCookieIsExpire(cookies) {
    if (!cookies) {
        return false
    }

    if (typeof cookies === 'string') {
        cookies = parseCookies(cookies)
    }

    if (!checkCookieField(cookies)) {
        return false
    }
    const dateObj = new Date(cookies['PHPSESSID'].expires);
    let timestamp = dateObj.getTime()
    return timestamp < new Date().getTime()
}

function checkCookieField(cookie_obj) {
    return 'PHPSESSID' in cookie_obj
}


function generateRandomString(length) {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';

    for (let i = 0; i < length; i++) {
        const randomIndex = Math.floor(Math.random() * characters.length);
        result += characters.charAt(randomIndex);
    }

    return result;
}

function gbkToUtf8(gbkStr) {
    return iconv.decode(gbkStr, 'gbk')
}

function utf16ToUtf8(utf16String) {
    // 将UTF-16BE编码的字符串转换为Buffer对象
    const buffer = Buffer.from(utf16String, 'ucs2');

// 将Buffer对象从UTF-16BE转换为UTF-8
    return iconv.decode(buffer, 'utf8');
}

function getEncodingType(str) {
    const encoder = new TextEncoder();
    try {
        // 将字符串转换为Uint8Array数组
        const uint8Arr = encoder.encode(str);

        if (uint8Arr[0] === 239 && uint8Arr[1] === 187 && uint8Arr[2] === 191) {
            return "UTF-8";
        } else if ((uint8Arr[0] & 0xF0) === 0xE0) {
            return "UTF-16BE";
        } else if ((uint8Arr[0] & 0xFC) === 0xC0) {
            return "UTF-16LE";
        } else {
            return "Unknown encoding type.";
        }
    } catch (error) {
        throw error;
    }
}

function unicodeToUtf8(unicodeString) {
    const utf16String = JSON.parse('"' + unicodeString + '"');
    const utf8Array = new TextEncoder().encode(utf16String);
    return String.fromCharCode.apply(null, utf8Array);
}

function parseCookies(cookieString) {
    const cookies = {};

    if (!cookieString) {
        return cookies
    }

    // 分割Cookie字符串
    const cookieArray = cookieString.split(/,\s+(?=[^;,]*=)/);

    // 遍历每个Cookie
    for (const cookie of cookieArray) {
        let cookiesObj = {};
        // 分割每个Cookie的键值对
        const keyValueArray = cookie.split('; ');

        // 取第一个键值对作为Cookie的主体
        const [cookieValue, ...attributes] = keyValueArray;

        // 分割键值对
        const [key, value] = cookieValue.split('=');

        // 添加到对象中
        cookies[key] = cookiesObj;
        cookiesObj.value = value
        // 处理Cookie的属性
        for (const attribute of attributes) {
            const [attrKey, attrValue] = attribute.split('=');
            // 去除前导空格
            const trimmedAttrKey = attrKey.trim();
            // 如果没有值，则默认为true
            // 添加属性到对象中
            cookiesObj[trimmedAttrKey] = attrValue ? attrValue.trim() : true;
        }
    }

    return cookies;
}

function parseSetCookie(cookies) {
    if (typeof cookies === 'string') {
        cookies = parseCookies(cookies)
    }
    const cookieArr = []
    for (let key in cookies) {
        cookieArr.push(key + "=" + cookies[key].value)
    }
    return cookieArr.join("; ")
}

const retry = async function (fun, num = 2) {
    let i = 0
    while (i < num) {
        if (await fun() === true) {
            break
        }
        i++
    }

}

function md5(password) {
    let md5Al = crypto.createHash('md5');
    return md5Al.update(password).digest('hex');
}

function extractCookieValues(cookies) {
    const cookieValues = [];
    cookies.forEach(cookie => {
        cookie.split("; ").forEach(item => {
            const [name, value] = item.split('=');
            cookieValues[name] = value
        })
    });
    return cookieValues;
}


module.exports = {
    checkCookieIsExpire
    , generateRandomString
    , unicodeToUtf8
    , parseCookies
    , checkCookieField
    , parseSetCookie
    , retry
    , utf16ToUtf8
    , md5
    , extractCookieValues
}

